package work.comeback.omo.util.configuration;

import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.util.configuration.interfaces.DatabaseConfigure;
import work.comeback.omo.util.configuration.model.AppConfig;
import work.comeback.omo.util.configuration.service.DatabaseService;
import work.comeback.omo.util.configuration.service.DbConfigFactory;

import java.sql.Connection;

public class Application {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);
    private static volatile Application instance;
    protected DatabaseConfigure databaseConfig;
    @Getter
    private AppConfig appConfig;
    @Getter
    private DatabaseService databaseService;
    @Getter
    private Connection connection;

    // instance design
    private Application() {
        loadConfig();
    }

    // get public method
    public static Application getInstance() {
        if (instance == null) {
            synchronized (Application.class) {
                if (instance == null) {
                    instance = new Application();
                }
            }
        }
        return instance;
    }

    // load config
    private void loadConfig() {
        try {
            this.appConfig = new AppConfig("application.properties", "chatbot.properties", "database.properties");

            // load db config
            this.databaseConfig = DbConfigFactory.create(appConfig.getConfigOptions());

            // load db service
            this.databaseService = new DatabaseService(databaseConfig);

            // setting conn
            this.connection = this.databaseService.connect();
        } catch (Exception e) {
            logger.error("Setup error: {}", e.getMessage());
            System.exit(-1);
        }
    }
}
